# -*- encoding=UTF-8 -*-
__author__ = "zichuanlu"

import os
import datetime
import threading


class read_serial(threading.Thread):

    def __init__(self, com):
        threading.Thread.__init__(self)
        self.com = com
        self.isRun = True

    def set_log_path(self, log_path):
        self.log_path = log_path

    def run(self):
        """
        读取串口
        :return:
        """
        while self.isRun:
            data = self.com.readline()
            self.write_txt(str(data), log_path=self.log_path)

    def stop(self):
        self.isRun = False

    def write_txt(self, str, log_path):
        """
        写入日志文件
        :param str:
        :return:
        """
        if not os.path.exists(os.path.dirname(log_path)):
            os.makedirs(os.path.dirname(log_path))

        log_dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')
        with open(log_path, "a") as f:
            f.write(log_dt + ' ' + str + '\n')
            f.close()


class write_serial(threading.Thread):

    def __init__(self, com):
        threading.Thread.__init__(self)
        self.command = None
        self.com = com

    def run(self):
        self.com.write(self.command.encode("utf-8"))
        self.com.write("\r\n".encode("utf-8"))

    def setCommand(self, command):
        self.command = command
